﻿using RpcHelper;
using RpcSync.Model;
using RpcSync.Model.DB;

namespace RpcSync.DAL.Repository
{
    internal class AccreditTokenDAL : IAccreditTokenDAL
    {
        private IRpcExtendResource<AccreditTokenModel> _BasicDAL;
        public AccreditTokenDAL(IRpcExtendResource<AccreditTokenModel> dal)
        {
            _BasicDAL = dal;
        }

        public void Add(AccreditTokenModel add)
        {
            this._BasicDAL.Insert(add);
        }
        public bool Delete(Guid id)
        {
            return this._BasicDAL.Delete(a => a.AccreditId == id);
        }

        public AccreditTokenDatum Get(Guid id)
        {
            return this._BasicDAL.Get(a => a.AccreditId == id, a => new AccreditTokenDatum
            {
                AccreditId = a.AccreditId,
                AccreditRole = a.AccreditRole,
                ApplyId = a.ApplyId,
                PAccreditId = a.PAccreditId,
                CheckKey = a.CheckKey,
                Expire = a.Expire,
                OverTime = a.OverTime,
                State = a.State,
                SysGroup = a.SysGroup,
                RoleType = a.RoleType,
                StateVer = a.StateVer,
                RpcMerId = a.RpcMerId,
                SystemType = a.SystemType
            });
        }

        public void SetOverTime(Guid accreditId, DateTime overTime)
        {
            if (!this._BasicDAL.Update(new AccreditTokenModel
            {
                OverTime = overTime,
                AccreditId = accreditId
            }, new string[]
            {
                "OverTime"
            }))
            {
                throw new ErrorException("accredit.db.set.fail");
            }
        }

        public Guid[] GetSubId(Guid accreditId)
        {
            return this._BasicDAL.Gets(a => a.PAccreditId == accreditId, a => a.AccreditId);
        }

        public bool Set(Guid accreditId, AccreditTokenSet set)
        {
            return this._BasicDAL.Update(set, a => a.AccreditId == accreditId && a.StateVer < set.StateVer);
        }
    }
}
